package com.example.demo.service.impl;

import com.example.demo.domain.UserAccount;
import com.example.demo.mapper.LoginMapper;
import com.example.demo.service.LoginService;
import com.schx.budget.exception.LoginException;
import com.schx.budget.util.JwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Override
    public String doLogin(UserAccount account) {
        UserAccount msg = loginMapper.getAccount(account.getOrgid());

        if(msg==null){
            throw new LoginException( "{\"code\":"+201+" ,\"data\":\"帐号或密码有误！\"}");
        }

        String password=DigestUtils.md5Hex(account.getPassword());
        if(!password.equalsIgnoreCase(msg.getPassword())){
            System.out.println(msg.getPassword());
            throw new LoginException( "{\"code\":"+201+" ,\"data\":\"帐号或密码有误！\"}");
        }

        //过期时间
        LocalDate localDate = LocalDate.now().plusDays(3);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        Date date = Date.from(zonedDateTime.toInstant());

        //生成令牌
        Map<String,Object> chain=new HashMap<>();
        chain.put("orgid",account.getOrgid());
        chain.put("orgName",msg.getOrgName());
        String token = JwtUtil.createToken(date, chain);
        return token;
    }

    @Override
    @Transactional
    public String editPassword(UserAccount account) {
        //加密
        String newPassword=DigestUtils.md5Hex(account.getNewPassword());

        //验证
        UserAccount msg = loginMapper.getAccount(account.getOrgid());

        if(msg==null){
            throw new LoginException( "{\"code\":"+500+" ,\"data\":\"密码有误！\"}");
        }

        String password=DigestUtils.md5Hex(account.getPassword());
        if(!password.equalsIgnoreCase(msg.getPassword())){
            throw new LoginException( "{\"code\":"+500+" ,\"data\":\"密码有误！\"}");
        }

        //修改
        int rows = loginMapper.editPassword(account.getOrgid(), newPassword);
        if(rows<1){
            throw new LoginException( "{\"code\":"+500+" ,\"data\":\"修改失败，请重试！\"}");
        }
        return "{\"code\":"+200+" ,\"data\":\"修改成功！\"}";
    }

    @Override
    public List<UserAccount> listOrg() {
        return loginMapper.listOrg();
    }
}
